import datetime
from ldap3 import *
import string
import random

from mysql_model import *

# 默认的路由访问方法，测试时使用get方法，正式上线方便切换到post方法
DEFAULT_METHODS = ['POST', 'GET']
API_METHODS = ['POST']
LAYUI_TABLE_DATA = {'code': None, }


def random_password(x):
    if x < 8 or x > 16:
        x = 12
    chosen1 = random.sample(string.ascii_lowercase, 3)
    chosen2 = random.sample(string.ascii_uppercase, 3)
    chosen3 = random.sample(string.digits, x - 6)
    password = "".join(random.sample(chosen3 + chosen2 + chosen1, x))

    return password


def random_name(x):
    if x < 6 or x > 16:
        x = 6
    name = "".join(random.sample(random.sample(string.ascii_lowercase, x), x))

    return name


def list_to_tree2(data, parent_id):
    """
    废弃
    备份一下之前的方法
    生成json树形图
    :param data:
    :param parent_id:
    :return:
    """
    out = {
        parent_id: {'dn': parent_id, 'parent_id': parent_id, 'name': "公司", 'name_dn': parent_id, 'children': []}
    }
    for p in data:
        out.setdefault(p['parent_id'], {'children': []})
        out.setdefault(p['dn'], {'children': []})
        out[p['dn']].update(p)
        out[p['parent_id']]['children'].append(out[p['dn']])
    return out[parent_id]


def list_to_tree(data, parent_id):
    """
    生成json树形图
    :param data:
    :param parent_id:
    :return:
    """
    out = {
        parent_id: {'id': 0, 'dn': parent_id, 'parent_id': parent_id, 'title': "公司", 'name': "公司",
                    'name_dn': parent_id, 'children': []}
    }
    for p in data:
        out.setdefault(p['parent_id'], {'children': []})
        out.setdefault(p['dn'], {'children': []})
        out[p['dn']].update(p)
        out[p['parent_id']]['children'].append(out[p['dn']])
    return out[parent_id]
    # return out


def check_dn(base_dc, add_dc):
    a = base_dc.lower().replace('dc=', '').split(',')
    b1 = add_dc.split(',')[-2].lower().replace('dc=', '')
    b2 = add_dc.split(',')[-1].lower().replace('dc=', '')

    if a[0] == b1 and a[1] == b2:
        return 0
    else:
        return 1


def init():
    """
    初始化检测
    如果本地有first文件，则说明是第一次运行，执行if部分的代码进行初始化数据库
    :return:
    """
    # msg = ''
    try:
        if os.path.exists('.\\first'):
            print('初始化标记文件存在，初始化检测')
            try:
                name = random_name(6)
                password = random_password(10)
                user = Users(username=name)
                user.set_password(password)
                user.validate_password(password)
                web = WebConfig(port=80)
                db.create_all()

                db.session.add(user)
                db.session.add(web)
                msg = f'用户名:{name},密码:{password}'
                # 提交任务
                db.session.commit()
                os.remove('.\\first')
                with open('ReadMe.txt', 'a', encoding='utf8') as f:
                    f.writelines('\n')
                    f.writelines(msg)
                msg = '初始化完成'
                import subprocess
                path = r'.\ReadMe.txt'
                subprocess.Popen(['notepad.exe', path])
            except Exception as e:
                print(e)
                with open(basedir + '\info.log', 'a', encoding='utf8') as f:
                    f.writelines(str(e))
                msg = f'错误：{e}'
                exit(msg)
        else:
            msg = '无需初始化'
            pass
    except Exception as e:
        msg = f'错误{e}'

    return msg


def check_server(host, port, username, password):
    """
    检测服务器连通性
    :param host: 主机名，可以是域名，也可以是IP地址
    :param port: 端口号，默认是636
    :param username: AD服务器管理员账号
    :param password: AD服务器管理员密码
    :return:
    """
    msg = []
    try:
        # 验证服务器地址和端口
        server = Server(host=host, port=port, use_ssl=True, get_info=ALL)
        Connection(server=server, auto_bind=True)
        # print(server)
        # print('连接成功')
        # print(str(server.info))
        dc = str(server.info).split('\n')[3].strip()
        # print('dc信息为：', dc)
        msg.append('服务器访问正常')
    except:
        # print('服务器无法访问，请检查后重新输入')
        msg.append('服务器无法访问')
        return 1, msg
    try:
        conn = Connection(server=server, user=dc.split(',')[0].split('=')[-1] + '\\' + username,
                          password=password,
                          authentication=NTLM, auto_bind=True)
        # print(conn.extend.standard.who_am_i(), '验证通过')
        # msg = '验证通过'
        msg.append('账号密码验证通过')
        # 创建一个ou，自主注册的用户都在此ou里
        dn = ('OU=自主注册,'+dc).split(',')
        conn.add(dn, 'organizationalUnit')
    except:
        # print('用户名或密码不正确，请重新输入')
        msg.append('登录失败,用户名或密码不正确')
        return 1, msg
    try:
        data = ServerConfig(server_name='默认服务器', host=host, port=port, base_dc=dc, username=username,
                            password=password,
                            date_time=datetime.datetime.now())
        db.session.add(data)
        db.session.commit()
        msg.append('记录服务器信息完毕')
    except:
        msg.append('记录服务器信息失败')
        return 1, msg
    return 0, msg
